import * as news from '@/api/news.js'
import * as resume from '@/api/resume.js'
import * as index from '@/api/index.js'
import * as user from '@/api/user.js'
import emoji from "@/emoji/m-emoji/m-emoji_2.0.0/emoji.js";
export default {
	data() {
		return {
			Type: uni.getStorageSync('Type'),
			stickyHeight: '',
			height: '',
			chatHeight: 0,
			focu: false, //输入框状态
			boxHeight: 0,
			Type: '', //身份
			uuid: '', //对方的userId
			currentUser: '', //用户信息
			messages: [], //消息列表
			content: '', //input内容
			quickList: [], //常用语列表
			emojiData: [], //表情列表
			friend: {}, //对方的信息
			positionForm: {
				page: 1,
				pages: 99999,
				state: 1,
				is_closure: 0
			}, //需求列表
			positionList: [], //需求列表
			resumeList: [], //接单列表
			addshow: false, //添加
			status: 0,
			textarea: '', //常用语
			textForm: {
				id: '',
				txt: '',
				type: ''
			},
			backIndex: null,
			params: {

			},
			hold: true,
			osName: '',
			osVersion: ''
			// chatsbox: '0rpx'
		}
	},
	onLoad(params) {
		let that = this
		uni.getSystemInfo({
			success: function(res) {
				that.osName = res.osName
				that.osVersion = res.osVersion
			}
		});
		//#ifdef APP-PLUS
		that.hold = true
		//#endif
		//#ifdef MP-WEIXIN
		this.hold = false
		//#endif
		// 动态获取键盘的高度
		uni.onKeyboardHeightChange(res => {
			if (res.height == '0') {
				this.height = 'calc(30rpx + env(safe-area-inset-bottom))'
				this.chatHeight = 0
			} else {
				this.height = res.height + 'px'
				this.chatHeight = +res.height
			}
			console.log(this.boxHeight, this.chatHeight, '键盘高度');
		})
		// const query = uni.createSelectorQuery().in(this)
		// query.select('.chat-box').boundingClientRect(data => {
		// 		console.log(data.height)
		// 		this.chatsbox = data.height + 'rpx'
		// 	})
		// 	.exec();
		this.params = params
		this.getuserInfo()
		this.getMemberPositionList()
		this.getMemberResumeInfo()
		this.getMessageQuickList()
		this.getEmoji()

		this.Type = uni.getStorageSync("Type")
		this.uuid = params.userId
		// 根据用户id获取聊天信息
		this.getMessageInfo(params.userId)
		//监听消息
		this.initialGoEasyListeners();
		//获取历史消息
		this.loadHistoryMessage(true);
		// if (uni.getStorageSync('Type') == 0) {
		// 	if (this.messages.some(item => item.payload.id == params.id)) {} else {
		// 		if (params.title) {
		// 			let pms = {}
		// 			pms.title = params.title
		// 			pms.id = params.id
		// 			this.getMemberPositionInfo(params.id)
		// 			this.sendCustom(pms)
		// 		}
		// 	}
		// }

	},
	onPullDownRefresh(e) { //下拉
		this.loadHistoryMessage(false); //加载
	},
	onUnload() {
		//退出聊天页面之前，清空监听器
		this.goEasy.im.on(this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, () => {});
		this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, () => {});
	},
	mounted() {
		uni.createSelectorQuery().in(this).select(".sticky").boundingClientRect(data => {
			this.stickyHeight = data.height + 'px'
		}).exec()
		uni.createSelectorQuery().in(this).select(".chat-box").boundingClientRect(data => {
			this.boxHeight = +data.height + 10
		}).exec()
	},
	methods: {
		// 获取用户信息
		getuserInfo() {
			user.getUserInfo({
				type: uni.getStorageSync('Type')
			}).then(res => {
				this.currentUser = res.data
			})
		},
		// 获取聊天信息
		getMessageInfo(id) {
			news.getMessageInfo({
				member_id: id,
				type: uni.getStorageSync('Type')
			}).then(res => {
				this.friend = res.data
				uni.setNavigationBarTitle({
					title: res.data.nickname
				});
			})
		},
		//查询需求列表
		getMemberPositionList() {
			resume.getMemberPositionList(this.positionForm).then(res => {
				this.positionList = res.data.data
			})
		},
		// 查询用户接单
		getMemberResumeInfo() {
			resume.getMemberResumeInfo().then(res => {
				this.resumeList = res.data
				this.getMemberResumeEducateList()
				this.getMemberResumeExperienceList()
			})
		},
		// 查询教育经历列表
		getMemberResumeEducateList() {
			resume.getMemberResumeEducateList().then(res => {
				this.resumeList.school = res.data
			})
		},
		// 查询案例展示列表
		getMemberResumeExperienceList() {
			resume.getMemberResumeExperienceList().then(res => {
				this.resumeList.experienceList = res.data
			})
		},
		//收藏接单
		collect() {
			index.memberCollectPosition({
				collect_id: this.friend.uuid,
				type: 0
			}).then(res => {
				this.getMessageInfo(this.friend.uuid)
			})
		},
		//获取常用语
		getMessageQuickList() {
			news.getMessageQuickList({
				type: uni.getStorageSync('Type')
			}).then(res => {
				this.quickList = res.data
			})
		},
		//获取表情
		getEmoji() {
			var page = Math.ceil(emoji.length / 21);
			for (let i = 0; i < page; i++) {
				this.emojiData[i] = [];
				for (let k = 0; k < 21; k++) {
					emoji[i * 21 + k] ? this.emojiData[i].push(
						emoji[i * 21 + k]
					) : ''
				}
			}
		},
		//监听消息
		initialGoEasyListeners() {
			// 监听私聊消息
			this.goEasy.im.on(this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, (message) => {
				let senderId = message.senderId;
				let receiverId = message.receiverId;
				let friendId = this.currentUser.uuid === senderId ? receiverId : senderId;
				if (friendId === this.uuid) {
					this.messages.push(message);
					this.markPrivateMessageAsRead();
				}
			});
			//监听消息删除
			this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, (deletedMessages) => {
				deletedMessages.forEach(message => {
					let senderId = message.senderId;
					let receiverId = message.receiverId;
					let friendId = this.currentUser.uuid === senderId ? receiverId : senderId;
					if (friendId === this.friend.uuid) {
						let index = this.messages.indexOf(message);
						if (index > -1) {
							this.messages.splice(index, 1);
						}
					}
				});
			});
		},
		//标记私聊
		markPrivateMessageAsRead() {
			this.goEasy.im.markPrivateMessageAsRead({
				userId: this.uuid,
				onSuccess: function() {
					console.log('标记私聊已读成功');
				},
				onFailed: function(error) {
					console.log("标记私聊已读失败", error);
				}
			});
		},
		// 撤回消息后的重新编辑
		editRecalledMessage(txt) {
			this.content = txt
			this.focu = true
		},
		// goeazy获取历史消息
		loadHistoryMessage(scrollToBottom) { //历史消息
			let that = this
			let lastMessageTimeStamp = null;
			let lastMessage = this.messages[0];
			if (lastMessage) {
				lastMessageTimeStamp = lastMessage.timestamp;
			}
			that.goEasy.im.history({
				userId: this.uuid,
				lastTimestamp: lastMessageTimeStamp,
				limit: 30,
				onSuccess: (result) => {
					// that.to_bottom()
					uni.stopPullDownRefresh(); //停止下拉刷新
					var messages = result.content;

					if (messages.length === 0) {
						// this.allHistoryLoaded = true;
					} else {
						this.messages = messages.concat(this.messages);
						if (scrollToBottom) {
							//收到的消息设置为已读
							// that.to_bottom()
							setTimeout(function() {
								uni.pageScrollTo({
									scrollTop: 100000,
									duration: 200
								})
							}, 500);
							this.markPrivateMessageAsRead();
						}
					}

					if (scrollToBottom == true && that.params.id && uni.getStorageSync('Type') == 1) {
						let textMessage = that.goEasy.im.createTextMessage({
							text: '您好，请问您现在还在找需求吗',
							to: {
								id: that.uuid,
								type: that.GoEasy.IM_SCENE.PRIVATE,
								data: {
									nickname: that.friend.nickname,
									avatar: that.friend.avatar
								}
							},
							notification: {
								title: that.currentUser.nickname + '发来一段文字',
								body: '您好，请问您现在还在找需求吗'
							}
						});
						if (result.content.length > 0) {
							var lasttime = new Date(parseInt(result.content[result.content.length - 1]
								.timestamp)).getDate();
						} else {
							var lasttime = -1
						}
						var nowtime = new Date(parseInt(textMessage.timestamp)).getDate();
						if (nowtime > lasttime) {
							that.sendMessage(textMessage);
						}
					}
					if (scrollToBottom == true && that.params.id && uni.getStorageSync('Type') == 0) {
						let pms = {}
						pms.title = that.params.title
						pms.id = that.params.id
						that.getMemberPositionInfo(pms.id)
						that.sendCustom(pms)
						let textMessage = that.goEasy.im.createTextMessage({
							text: '请问贵公司的' + that.params.title + '还有空缺吗?',
							to: {
								id: that.uuid,
								type: that.GoEasy.IM_SCENE.PRIVATE,
								data: {
									nickname: that.friend.nickname,
									avatar: that.friend.avatar
								}
							},
							notification: {
								title: that.currentUser.nickname + '发来一段文字',
								body: '请问贵公司的' + pms.title + '还有空缺吗?',
							}
						});
						if (result.content.length > 0) {
							var lasttime = new Date(parseInt(result.content[result.content.length - 1]
								.timestamp)).getDate();
						} else {
							var lasttime = -1
						}
						var nowtime = new Date(parseInt(textMessage.timestamp)).getDate();
						if (nowtime > lasttime) {
							setTimeout(() => {
								that.sendMessage(textMessage);
							}, 500)
						}
					}
				},
				onFailed: (error) => {
					console.log('获取历史消息失败:', error);
					uni.stopPullDownRefresh(); //停止下拉刷新
				}
			});
		},
		//发送文字消息
		createTextMessage() {
			let that = this
			this.forMessageList()
			if (this.content !== '') {
				let body = this.content;
				if (this.content.length >= 50) {
					body = this.content.substring(0, 30) + '...';
				}
				let textMessage = this.goEasy.im.createTextMessage({
					text: this.content,
					to: {
						id: this.uuid,
						type: this.GoEasy.IM_SCENE.PRIVATE,
						data: {
							nickname: this.friend.nickname,
							avatar: this.friend.avatar,
						}
					},
					notification: {
						title: this.currentUser.nickname + '发来一段文字',
						body: body
					}
				});
				this.sendMessage(textMessage);
			}
			this.content = '';
		},
		// 消息列表循环
		forMessageList() {
			let sendArr = []
			this.messages.forEach(item => {
				sendArr.push(item.senderId)
			})
			this.forMessage = sendArr.indexOf(this.currentUser.uuid)
		},
		//goeazy发消息
		sendMessage(message) {
			let that = this
			this.goEasy.im.sendMessage({
				message: message,
				onSuccess: function(message) { //发送成功
					// that.$tools.toast('发送成功')
					that.messages.push(message);
					that.totuisong()
					that.focu = false
					that.memberPush(message)
					that.addshow = false
					that.to_bottom()
				},
				onFailed: function(error) { //发送失败
					that.addshow = false
					console.log(error);
				}
			});
		},
		// 通知和透传推送消息
		memberPush(message) {
			if (message.type == 'text') {
				let form = {}
				form.type = message.type
				form.text = message.payload.text
				form.member_id = this.friend.uuid.replace('p', '')
				form.name = this.currentUser.name
				news.memberPush(form).then(res => {})
				news.memberPushTransmission(form).then(res => {})
			}
		},
		//发送短信
		totuisong() {
			let form = {}
			let type = uni.getStorageSync('Type')
			if (type == 1) {
				form.type = 0
			} else if (type == 0) {
				form.type = 1
			}
			form.member_id = this.friend.uuid.replace('p', '')
			news.totuisong(form).then(res => {})
		},
		//发送需求
		sendPosition(item) {
			let that = this
			let position = item
			let customMessage = this.goEasy.im.createCustomMessage({
				type: 'positions', //type 用来分辨自定义消息
				payload: position, //发送内容
				to: { //发送给
					id: this.uuid,
					type: this.GoEasy.IM_SCENE.PRIVATE,
					data: {
						nickname: this.friend.nickname,
						avatar: this.friend.avatar
					}
				},
				notification: {
					title: this.currentUser.nickname + '发来一份需求',
					body: '[需求]' // 字段最长 50 字符
				}
			});
			this.sendMessage(customMessage);
		},
		//打招呼
		sendCustom(item) {
			let that = this
			let custom = item
			let customMessage = this.goEasy.im.createCustomMessage({
				type: 'custom', //type 用来分辨自定义消息
				payload: custom, //发送内容
				to: { //发送给
					id: this.uuid,
					type: this.GoEasy.IM_SCENE.PRIVATE,
					data: {
						nickname: this.friend.nickname,
						avatar: this.friend.avatar
					}
				},
				notification: {
					title: this.currentUser.nickname + '发来一份消息',
					body: '[打招呼]' // 字段最长 50 字符
				}
			});
			this.sendMessage(customMessage);
			// this.createTextMessageto(content)
		},
		//发送图片
		createImageMessage() {
			this.forMessageList()
			let that = this
			uni.chooseImage({
				count: 1,
				success: (res) => {
					res.tempFiles.forEach(file => {
						let imageMessage = this.goEasy.im.createImageMessage({
							to: {
								id: this.friend.uuid,
								type: this.GoEasy.IM_SCENE.PRIVATE,
								data: {
									nickname: this.friend.nickname,
									avatar: this.friend.avatar
								}
							},
							file: file,
							onProgress: function(progress) {
								console.log(progress);
							},
							notification: {
								title: this.currentUser.nickname + '发来一张图片',
								body: '[图片消息]' // 字段最长 50 字符
							}
						});
						this.sendMessage(imageMessage);
					})
				}
			});
		},
		//查看图片
		imageSee(item) {
			uni.previewImage({
				current: 0,

				urls: [item.payload.url],

				longPressActions: {
					itemList: ['发送给朋友', '保存图片', '收藏'],

					success: function(data) {
						console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片')
					},

					fail: function(err) {
						console.log(err.errMsg)
					}
				}
			})
		},
		//发送接单消息
		sendResume() {
			let that = this
			// return;
			let customMessage = this.goEasy.im.createCustomMessage({
				type: 'resumes', //type 用来分辨自定义消息
				payload: this.resumeList, //发送内容
				to: { //发送给
					id: this.uuid,
					type: this.GoEasy.IM_SCENE.PRIVATE,
					data: {
						nickname: this.friend.nickname,
						avatar: this.friend.avatar
					}
				},
				notification: {
					title: this.currentUser.nickname + '发来一份接单',
					body: '[接单投递]' // 字段最长 50 字符
				}
			});
			this.sendMessage(customMessage);

		},
		//查看需求
		goPosition(item) {
			if (uni.getStorageSync('Type') == 0) {
				this.$tools.navigate(`/pages/home/jobDetails/index?position_id=${item.payload.id}`)
			}
		},
		// 查看接单
		goResume(item) {
			if (uni.getStorageSync('Type') == 1) {
				this.$tools.navigate(`/pages/home/resumeInfo/index?resume_id=${item.payload.member_id}`)
			}
		},
		// 根据id查询需求详情
		getMemberPositionInfo(id) {
			index.getPositionInfo({
				position_id: id
			}).then(res => {
				let form = {
					age: {},
					areas: {},
					company: {},
					drving: {}
				}
				form.age.title = res.data.age_id
				form.areas.title = res.data.areas_id
				form.drving.title = res.data.drving_id
				form.id = res.data.id
				form.is_closure = res.data.is_closure
				form.secondary = res.data.secondary
				form.state = res.data.state
				form.stitle = res.data.salary_text
				form.title = res.data.title
				form.company.name = this.friend.nickname
				this.sendPosition(form)
			})
		},
		// 页面滚动到底部
		to_bottom() {
			setTimeout(function() {
				uni.pageScrollTo({
					scrollTop: 100000,
					duration: 100
				})
			}, 100);
		},
		focus() {
			this.addshow = false
			//#ifdef APP-PLUS
			setTimeout(function() {
				uni.pageScrollTo({
					scrollTop: 100000,
					duration: 200
				})
			}, 200);
			//#endif
		},
		// 点击输入区域加号
		add() {
			setTimeout(() => {
				if (this.status == 0) {
					this.addshow = !this.addshow
				} else {
					this.addshow = true
				}
				this.status = 0
			}, 100)
		},
		// 关闭所有
		closeAll() {
			this.addshow = false
			this.status = 0
		},
		// 点击输入区域表情
		emojiClick() {
			setTimeout(() => {
				if (this.status == 4) {
					this.addshow = !this.addshow
				} else {
					this.addshow = true
				}
				this.status = 4

			}, 0)
		},
		zhiweiBnt() {
			this.status = 1
		},
		//常用语点击
		quickShow() {
			this.$tools.toast(this.focu)
			setTimeout(() => {
				if (this.status == 2) {
					this.focu = true
					this.addshow = false
					this.status = 0
				} else {
					this.addshow = true
					this.status = 2
				}
			}, 100)
		},
		// 点击表情时间
		pushEmoji(item) {
			// this.addshow = false
			this.content = this.content + item
			// this.focu = true
			// this.status = 0
		},
		poinblur() {
			this.focu = false
			if (this.osName == 'android' && this.osVersion < 10) {
				this.height = 'calc(30rpx + env(safe-area-inset-bottom))'
				this.chatHeight = 0
			}
		},
		//点击常用语
		quickText(item) {
			this.content = item.txt
			this.focu = true
			this.addshow = false
			this.status = 0
		},
		//添加常用语
		addQuick() {
			this.textForm.type = uni.getStorageSync('Type')
			this.textForm.txt = ''
			this.textForm.id = ''
			this.$refs.popup.open()
		},
		//编辑常用语
		editQuick(item) {
			this.textForm.type = uni.getStorageSync('Type')
			this.textForm.txt = item.txt
			this.textForm.id = item.id
			this.$refs.popup.open()
		},
		//管理常用语
		manage() {
			if (this.status == 2) {
				this.status = 3
			} else if (this.status == 3) {
				this.status = 2
			}
		},
		//删除快捷语
		deleteQuick(item) {
			let that = this
			let form = {}
			form.id = item.id
			form.del = 1
			form.type = uni.getStorageSync('Type')
			uni.showModal({
				title: '提示',
				content: '是否确认删除',
				success: function(res) {
					if (res.confirm) {
						news.saveMessageQuick(form).then(res => {
							that.$tools.toast('删除成功')
							that.getMessageQuickList()
						})
					} else if (res.cancel) {}
				}
			});
		},
		// 长按复制
		fuzhi(e) {
			var that = this
			uni.setClipboardData({
				//准备复制的数据
				data: e.payload.text,
				success: function(res) {
					uni.showToast({
						title: '复制成功',
						icon: 'none',
						duration: 2000
					});
					that.backIndex = null
				}
			});
		},
		//长按撤回
		cehui(e) {
			//   判断时间是否是3分钟之内的  三分钟之内才可以撤回
			//   e.timestamp  是发送的时间  
			//   e.senderId  是发送的id   判断是不是自己   e.senderId == this.currentUser.uuid
			const MAX_RECALLABLE_TIME = 3 * 60 * 1000 //3分钟以内的消息才可以撤回
			if (e.senderId == this.currentUser.id && (Date.now() - e.timestamp) < MAX_RECALLABLE_TIME) {
				this.goEasy.im.recallMessage({
					messages: [e],
					onSuccess: () => {
						console.log('撤回成功');
					},
					onFailed: (error) => {
						console.log('撤回失败,error:', error);
					}
				});
			} else {
				uni.showToast({
					title: '三分钟之内才可以撤回',
					icon: 'none',
					duration: 2000
				});
			}
			this.backIndex = null
		},
		//取消
		close() {
			this.$refs.popup.close()
			this.textarea = ''
		},
		report() {
			this.$tools.navigate('/pages/user/report/index?id=' + this.friend.uuid.replace('p', ''))
		},
		// 保存快捷语
		saveQuick() {
			news.saveMessageQuick(this.textForm).then(res => {
				this.getMessageQuickList()
				this.close()
			})
		},
		customs(item) {
			this.$tools.navigate(`/pages/home/jobDetails/index?position_id=${item.payload.id}`)
		},
		//打电话
		call() {
			if (uni.getStorageSync('Type') == 0) {
				news.memberGetCompanyTel({
					member_id: this.friend.uuid.replace('p', '')
				}).then(res => {
					uni.makePhoneCall({
						phoneNumber: res.data //仅为示例
					});
				})
			} else {
				index.memberGetResumeTel({
					resume_id: this.friend.uuid
				}).then(res => {
					uni.makePhoneCall({
						phoneNumber: res.data.tel //仅为示例
					});
				})
			}
		},
		// 查看接单
		lookResume() {
			if (this.friend.is_closure == 0) {
				this.$tools.navigate(`/pages/home/resumeInfo/index?resume_id=${this.friend.uuid}`)
			} else {
				this.$tools.toast('对方接单已隐藏')
			}
		},
		//长按
		longpress(index) {
			this.backIndex = index
		},
		// 处理时间格式(暂时没用上)
		beautify_time(timestamp) {
			var mistiming = (Math.round(Date.now()) - timestamp) / 1000;
			var postfix = mistiming > 0 ? '前' : '后'
			mistiming = Math.abs(mistiming)
			var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];
			var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];

			if (mistiming > 0) {
				for (var i = 0; i < 7; i++) {
					var inm = Math.floor(mistiming / arrn[i])
					if (inm != 0) {
						if (i == 3 && inm < 24) {
							// return this.formatDate(timestamp)
						}
						return inm + arrr[i] + postfix
					}
				}
			}
		},
		// 处理时间格式
		transferTime(time) {
			var now = new Date()
			var dd = new Date(time)
			if (now.getDate() == dd.getDate()) {
				return dd.getHours() + ':' + dd.getMinutes() + ':' + dd.getSeconds();
			} else {
				return dd.getMonth() + 1 + '月' + dd.getDate() + '日' + dd.getHours() + ':' + dd.getMinutes() + ':' + dd.getSeconds();
			}
		},
	}
}
